<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能助手</title>
    <style>
        /* CSS变量定义 */
        :root {
            --primary-color: #4f46e5;
            --primary-light: #818cf8;
            --primary-dark: #312e81;
            --secondary-color: #ec4899;
            --text-color: #1f2937;
            --text-secondary: #6b7280;
            --background-light: #f9fafb;
            --background-card: #ffffff;
            --border-color: #e5e7eb;
            --shadow-light: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
            --shadow-medium: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.03);
            --shadow-hover: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            --radius-sm: 8px;
            --radius-md: 16px;
            --radius-lg: 24px;
            --spacing-xs: 4px;
            --spacing-sm: 8px;
            --spacing-md: 16px;
            --spacing-lg: 24px;
            --spacing-xl: 32px;
            --font-size-sm: 14px;
            --font-size-base: 16px;
            --font-size-lg: 18px;
            --font-size-xl: 24px;
            --transition-fast: 0.15s ease;
            --transition-normal: 0.3s ease;
            --transition-slow: 0.5s ease;
        }
        
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, var(--background-light) 0%, #f0f9ff 100%);
            color: var(--text-color);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: var(--spacing-md);
        }
        
        /* 主容器 */
        .chat-wrapper {
            width: 100%;
            max-width: 900px;
            min-height: 80vh;
            max-height: 90vh;
            background: var(--background-card);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-medium);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            z-index: 1;
        }
        
        /* 背景装饰 */
        .chat-wrapper::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 300px;
            height: 300px;
            background: linear-gradient(135deg, var(--primary-light) 0%, var(--secondary-color) 100%);
            border-radius: 50%;
            transform: translate(50%, -50%);
            opacity: 0.05;
            z-index: -1;
        }
        
        /* 聊天头部 */
        .chat-header {
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            padding: var(--spacing-lg);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            overflow: hidden;
            box-shadow: var(--shadow-light);
        }
        
        .chat-header::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(50%, -50%);
        }
        
        .header-content {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
            position: relative;
            z-index: 1;
        }
        
        .logo {
            width: 40px;
            height: 40px;
            background: white;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .logo svg {
            width: 24px;
            height: 24px;
            fill: var(--primary-color);
        }
        
        .header-title {
            font-size: var(--font-size-lg);
            font-weight: 600;
            letter-spacing: 0.5px;
        }
        
        /* 聊天主体 */
        .chat-body {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        /* 消息容器 */
        .messages-container {
            flex: 1;
            padding: var(--spacing-lg);
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: var(--spacing-lg);
        }
        
        /* 自定义滚动条 */
        .messages-container::-webkit-scrollbar {
            width: 6px;
        }
        
        .messages-container::-webkit-scrollbar-track {
            background: var(--background-light);
            border-radius: 3px;
        }
        
        .messages-container::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
            transition: background var(--transition-fast);
        }
        
        .messages-container::-webkit-scrollbar-thumb:hover {
            background: var(--primary-light);
        }
        
        /* 消息组 */
        .message-group {
            display: flex;
            flex-direction: column;
            gap: var(--spacing-sm);
            max-width: 75%;
        }
        
        .message-group.user {
            align-self: flex-end;
        }
        
        .message-group.ai {
            align-self: flex-start;
        }
        
        /* 消息气泡 */
        .message {
            padding: var(--spacing-md) var(--spacing-lg);
            border-radius: var(--radius-md);
            font-size: var(--font-size-base);
            line-height: 1.5;
            position: relative;
            word-wrap: break-word;
            animation: fadeInUp 0.3s ease-out;
        }
        
        .message.user {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            border-bottom-right-radius: var(--spacing-xs);
            box-shadow: var(--shadow-light);
        }
        
        .message.ai {
            background: var(--background-light);
            color: var(--text-color);
            border-bottom-left-radius: var(--spacing-xs);
            border: 1px solid var(--border-color);
            box-shadow: var(--shadow-light);
        }
        
        /* 时间戳 */
        .timestamp {
            font-size: var(--font-size-sm);
            color: var(--text-secondary);
            align-self: flex-end;
            margin-top: var(--spacing-xs);
            opacity: 0.7;
        }
        
        .message-group.ai .timestamp {
            align-self: flex-start;
        }
        
        /* 输入区域 */
        .input-container {
            padding: var(--spacing-lg);
            background: var(--background-card);
            border-top: 1px solid var(--border-color);
            position: relative;
        }
        
        .input-wrapper {
            display: flex;
            gap: var(--spacing-md);
            align-items: flex-end;
        }
        
        .text-input {
            flex: 1;
            min-height: 48px;
            max-height: 120px;
            padding: var(--spacing-md) var(--spacing-lg);
            border: 2px solid var(--border-color);
            border-radius: 24px;
            font-size: var(--font-size-base);
            font-family: inherit;
            resize: none;
            outline: none;
            transition: all var(--transition-normal);
            background: var(--background-light);
        }
        
        .text-input:focus {
            border-color: var(--primary-light);
            background: white;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .text-input::placeholder {
            color: var(--text-secondary);
        }
        
        /* 发送按钮 */
        .send-button {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: all var(--transition-normal);
            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
            flex-shrink: 0;
        }
        
        .send-button:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
        }
        
        .send-button:active:not(:disabled) {
            transform: translateY(0);
        }
        
        .send-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .send-button svg {
            width: 20px;
            height: 20px;
        }
        
        /* 打字指示器 */
        .typing-indicator {
            display: inline-flex;
            gap: 4px;
            padding: var(--spacing-md) var(--spacing-lg);
            background: var(--background-light);
            border-radius: var(--radius-md);
            border: 1px solid var(--border-color);
            border-bottom-left-radius: var(--spacing-xs);
            align-self: flex-start;
        }
        
        .typing-indicator span {
            width: 8px;
            height: 8px;
            background: var(--primary-light);
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out both;
        }
        
        .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
        
        /* 初始加载 */
        .initial-loading {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100%;
            gap: var(--spacing-lg);
            color: var(--text-secondary);
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid var(--border-color);
            border-top: 3px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            font-size: var(--font-size-base);
            font-weight: 500;
        }
        
        /* 动画定义 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0.7);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @keyframes typewriter {
            from {
                opacity: 0;
                transform: translateY(2px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* 打字机效果字符 */
        .typewriter-char {
            display: inline-block;
            animation: typewriter 0.08s ease-out;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            :root {
                --spacing-lg: 20px;
                --spacing-xl: 24px;
                --font-size-lg: 16px;
            }
            
            .chat-wrapper {
                min-height: 95vh;
                max-height: 95vh;
                border-radius: var(--radius-md);
            }
            
            .message-group {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-wrapper">
        <!-- 聊天头部 -->
        <div class="chat-header">
            <div class="header-content">
                <div class="logo">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM12 20C7.59 20 4 16.41 4 12C4 7.59 7.59 4 12 4C16.41 4 20 7.59 20 12C20 16.41 16.41 20 12 20ZM12.5 7H11V13L16.2 16.2L17 14.9L12.5 12.2V7Z"/>
                    </svg>
                </div>
                <h1 class="header-title">AI智能助手</h1>
            </div>
        </div>
        
        <!-- 聊天主体 -->
        <div class="chat-body">
            <!-- 消息容器 -->
            <div class="messages-container" id="messages-container">
                <!-- 初始加载状态 -->
                <div class="initial-loading" id="initial-loading">
                    <div class="loading-spinner"></div>
                    <p class="loading-text">正在连接AI助手...</p>
                </div>
            </div>
            
            <!-- 输入区域 -->
            <div class="input-container">
                <div class="input-wrapper">
                    <textarea class="text-input" id="message-input" placeholder="输入您的问题..." rows="1" autocomplete="off"></textarea>
                    <button class="send-button" id="send-button" disabled>
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" fill="currentColor"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 获取DOM元素
            const messagesContainer = document.getElementById('messages-container');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const initialLoading = document.getElementById('initial-loading');
            
            // 自动调整输入框高度
            messageInput.addEventListener('input', () => {
                messageInput.style.height = 'auto';
                messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
                updateSendButtonState();
            });
            
            // 更新发送按钮状态
            function updateSendButtonState() {
                const hasContent = messageInput.value.trim().length > 0;
                sendButton.disabled = !hasContent;
            }
            
            // 隐藏初始加载动画
            function hideInitialLoading() {
                if (initialLoading) {
                    initialLoading.style.opacity = '0';
                    initialLoading.style.transition = 'opacity 0.5s ease-out';
                    initialLoading.style.height = '0';
                    initialLoading.style.margin = '0';
                    initialLoading.style.padding = '0';
                    initialLoading.style.overflow = 'hidden';
                    setTimeout(() => {
                        initialLoading.remove();
                    }, 500);
                }
            }
            
            // 添加消息到界面
            function addMessage(text, isUser = false) {
                const messageGroup = document.createElement('div');
                messageGroup.className = `message-group ${isUser ? 'user' : 'ai'}`;
                
                const message = document.createElement('div');
                message.className = `message ${isUser ? 'user' : 'ai'}`;
                message.textContent = text;
                
                const timestamp = document.createElement('div');
                timestamp.className = 'timestamp';
                const now = new Date();
                timestamp.textContent = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                messageGroup.appendChild(message);
                messageGroup.appendChild(timestamp);
                messagesContainer.appendChild(messageGroup);
                
                // 滚动到底部
                scrollToBottom();
            }
            
            // 添加打字指示器
            function addTypingIndicator() {
                // 先移除已有的打字指示器
                removeTypingIndicator();
                
                const typingIndicator = document.createElement('div');
                typingIndicator.className = 'typing-indicator';
                typingIndicator.id = 'typing-indicator';
                typingIndicator.innerHTML = '<span></span><span></span><span></span>';
                messagesContainer.appendChild(typingIndicator);
                
                // 滚动到底部
                scrollToBottom();
            }
            
            // 移除打字指示器
            function removeTypingIndicator() {
                const typingIndicator = document.getElementById('typing-indicator');
                if (typingIndicator) {
                    typingIndicator.remove();
                }
            }
            
            // 滚动到底部
            function scrollToBottom() {
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
            
            // 流式显示文本（修复同步问题）
            function streamTextDisplay(element, text, startIndex = 0) {
                return new Promise((resolve) => {
                    // 如果已经显示完所有文本，直接返回
                    if (startIndex >= text.length) {
                        resolve();
                        return;
                    }
                    
                    // 每次显示少量字符以避免阻塞UI
                    const batchSize = Math.min(3, text.length - startIndex);
                    const fragment = document.createDocumentFragment();
                    
                    for (let i = 0; i < batchSize && startIndex + i < text.length; i++) {
                        const charSpan = document.createElement('span');
                        charSpan.className = 'typewriter-char';
                        charSpan.textContent = text[startIndex + i];
                        charSpan.style.animationDelay = `${i * 15}ms`;
                        fragment.appendChild(charSpan);
                    }
                    
                    // 添加片段到DOM
                    element.appendChild(fragment);
                    
                    // 滚动到底部
                    scrollToBottom();
                    
                    // 继续显示下一批字符
                    if (startIndex + batchSize < text.length) {
                        setTimeout(() => {
                            streamTextDisplay(element, text, startIndex + batchSize).then(resolve);
                        }, 20); // 更小的延迟以提高响应速度
                    } else {
                        resolve();
                    }
                });
            }
            
            // 发送消息到后端
            async function sendMessage(question) {
                // 验证输入
                if (!question.trim()) return;
                
                // 获取输入内容并清空
                const userMessage = question.trim();
                messageInput.value = '';
                messageInput.style.height = 'auto';
                updateSendButtonState();
                
                // 添加用户消息
                addMessage(userMessage, true);
                
                // 添加打字指示器
                addTypingIndicator();
                
                try {
                    // 构建请求URL
                    const url = `/stream/chatflux3?question=${encodeURIComponent(userMessage)}`;
                    
                    // 发送请求
                    const response = await fetch(url);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    
                    // 获取响应流
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    
                    // 移除打字指示器
                    removeTypingIndicator();
                    
                    // 创建AI消息元素
                    const messageGroup = document.createElement('div');
                    messageGroup.className = 'message-group ai';
                    
                    const aiMessage = document.createElement('div');
                    aiMessage.className = 'message ai';
                    
                    const timestamp = document.createElement('div');
                    timestamp.className = 'timestamp';
                    const now = new Date();
                    timestamp.textContent = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
                    
                    messageGroup.appendChild(aiMessage);
                    messageGroup.appendChild(timestamp);
                    messagesContainer.appendChild(messageGroup);
                    
                    // 滚动到底部
                    scrollToBottom();
                    
                    // 累积的AI回复内容
                    let fullResponse = '';
                    let displayPromise = Promise.resolve(); // 保存当前正在显示的Promise
                    let lastUpdateTime = Date.now();
                    const minUpdateInterval = 100; // 最小更新间隔（毫秒）
                    
                    // 读取流数据
                    while (true) {
                        const { done, value } = await reader.read();
                        
                        if (done) {
                            break;
                        }
                        
                        // 解码数据
                        const chunk = decoder.decode(value, { stream: true });
                        
                        // 累积完整响应
                        fullResponse += chunk;
                        
                        // 限制更新频率，避免过于频繁的UI更新
                        const currentTime = Date.now();
                        if (currentTime - lastUpdateTime >= minUpdateInterval || done) {
                            // 等待之前的显示任务完成
                            await displayPromise;
                            
                            // 清空现有内容并显示完整响应
                            aiMessage.innerHTML = '';
                            displayPromise = streamTextDisplay(aiMessage, fullResponse);
                            
                            lastUpdateTime = currentTime;
                        }
                    }
                    
                    // 确保最后一部分内容也显示出来
                    await displayPromise;
                    
                } catch (error) {
                    console.error('Error sending message:', error);
                    removeTypingIndicator();
                    addMessage('抱歉，处理您的请求时出错了，请稍后再试。');
                }
            }
            
            // 绑定发送按钮点击事件
            sendButton.addEventListener('click', () => {
                sendMessage(messageInput.value);
            });
            
            // 绑定输入框回车事件（不按shift）
            messageInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage(messageInput.value);
                }
            });
            
            // 初始化
            updateSendButtonState();
            
            // 页面加载后发送问候消息
            setTimeout(() => {
                hideInitialLoading();
                sendMessage('你好，我是AI智能助手，有什么我可以帮助你的吗？');
            }, 1000);
        });
    </script>
</body>
</html>